<template>
  <div class="out-container">
    <cs-search ref="searchRef" title="用户列表" :span="8" direction="row" :data="searchData" @getData="getData" />
    <el-card style="margin-top: 10px;">
      <div slot="header" class="clearfix">
        <el-row type="flex" justify="end">
          <el-button size="mini" plain icon="el-icon-document" @click="handleTempl">模板</el-button>
          <el-button size="mini" plain icon="el-icon-upload2" @click="handleImportUser">导入</el-button>
          <el-button size="mini" type="primary" icon="el-icon-circle-plus" @click="openAddDialog(null, null)">新增</el-button>
          <input ref="excel-upload-input" hidden type="file" accept=".xls" @change="handleClick">
        </el-row>
      </div>
      <div>
        <vxe-grid ref="userTable" v-bind="tableOptions">
          <template #status="{ row }">
            <div class="flex-row flex-center" >
              <i :class="[ 'tag', row.status === '2' ? 'normal' : (row.status === '1' ? 'forbid' : 'delete') ]"/>
              <span v-if="row.status === '2'" class="normal">正常</span>
              <span v-else-if="row.status === '1'" class="forbid">禁用</span>
              <span v-else class="delete">删除</span>
            </div>
<!--            <el-tag-->
<!--              v-if="row.status === '2'"-->
<!--              effect="dark"-->
<!--              size="mini"-->
<!--              type="success"-->
<!--            >正常</el-tag>-->
<!--            <el-tag-->
<!--              v-else-if="row.status === '1'"-->
<!--              effect="dark"-->
<!--              size="mini"-->
<!--            >禁用</el-tag>-->
<!--            <el-tag v-else effect="dark" size="mini" type="warning">删除</el-tag>-->
          </template>
<!--          <template #roles="{ row }">-->
<!--            <el-tag effect="dark" size="mini" type="warning">{{ rolesName(row.roleId) }}</el-tag>-->
<!--          </template>-->
          <template #operate="{ row, rowIndex }">
            <el-popover
              placement="left-start"
              trigger="hover"
            >
              <el-row v-for="(item,index) in operatingData" :key="index">
                <el-button
                  type="text"
                  :icon="item.icon"
                  @click="item.name(rowIndex, row)"
                >
                  {{ item.title }}
                </el-button>
              </el-row>
              <el-button slot="reference" type="text">
                <svg-icon icon-class="cardHeaderIcon" style="font-size: 12px" />
              </el-button>
            </el-popover>
          </template>
        </vxe-grid>
        <div class="footer">
          <cs-page
            :page.sync="pageData.page"
            :limit.sync="pageData.size"
            :total="pageData.total"
            @pagination="findByPage"
          />
        </div>
      </div>
    </el-card>
    <user-edit ref="userEdit" @getData="findByPage" />
    <!-- 导入错误  -->
    <cs-dialog
      :dialog="errorDialogOption"
      @onSubmit="errorDialogOption.show = false"
    >
      <div slot="content">
        <vxe-grid ref="xTable" v-bind="gridOptions" />
      </div>
      <span slot="footer" />
    </cs-dialog>

  </div>
</template>

<script>
import { statisticsManager, uploadAdminExcel, delManager } from '@/api/userFile'
import UserEdit from './components/userEdit'
import { getRoleOption } from '@/api/system/role'
export default {
  name: 'Admin',
  components: { UserEdit },
  data() {
    const self = this
    const vxeTableOption = {
      size: 'small',
      headerAlign: 'center',
      border: 'inner', // default full outer inner none
      stripe: true,
      resizable: true,
      showOverflow: true,
      headerRowStyle: { backgroundColor: 'rgba(217, 223, 235, 0.2)' },
      align: 'center',
      data: []
    }
    return {
      errorDialogOption: {
        show: false,
        title: {
          title: '导入异常数据',
          icon: ''
        },
        width: '65%',
        top: '20px'
      },
      rolesOption: [],
      searchData: [
        { label: '姓名', model: 'name', type: 'input' }
      ],
      tableOptions: {
        ...vxeTableOption,
        height: self.$baseTableHeight(50),
        columns: [
          { type: 'seq', title: '序号', minWidth: 40 },
          { title: '姓名', field: 'name', minWidth: '100' },
          { title: '培训组', filed: 'groupName', minWidth: '100' },
          { title: '登录用户名', field: 'userName', minWidth: '120' },
          { title: '性别', field: 'gender', minWidth: '100', formatter: ({ cellValue }) => {
            if (cellValue === '0') {
              return '女'
            } else {
              return '男'
            }
          } },
          // { title: '身份证号', field: 'cardId', minWidth: '140' },
          { title: '手机号', field: 'phone', minWidth: '100' },
          // { title: '邮箱', field: 'mail', minWidth: '150' },
          // { title: '单位名称', field: 'companyName', minWidth: '180' },
          { title: '用户状态', field: 'status', minWidth: '80', slots: { default: 'status' }},
          { title: '人员角色', field: 'roleName', minWidth: '180'},
          { title: '操作', minWidth: 80, fixed: 'right', slots: { default: 'operate' }}
        ]
      },
      operatingData: [{
        title: '编辑',
        icon: 'el-icon-edit',
        name: self.openAddDialog
      }, {
        title: '删除',
        icon: 'el-icon-delete',
        name: self.handleRemove
      }],
      searchFormData: {},
      pageData: {
        page: 1,
        size: 10,
        total: 0
      },
      gridOptions: {
        ...vxeTableOption,
        columns: [
          { type: 'seq', title: '序号', minWidth: 20 },
          { title: '姓名', field: 'userName', minWidth: '100' },
          { title: '身份证号码', field: 'idCard', minWidth: '100' },
          { title: '错误信息', field: 'errorText', minWidth: '150' }
        ]
      }
    }
  },
  computed: {
    rolesName() {
      return (roleId) => {
        return this.rolesOption.find(item => item.value === roleId)?.label || ''
      }
    }
  },
  mounted() {
    // this.findByPage()
    getRoleOption().then(res => {
      this.rolesOption = res.data.result
    })
  },
  methods: {
    getData(data) {
      this.searchFormData = data
      this.pageData.page = 1
      this.findByPage()
    },
    /** 模板下载*/
    handleTempl() {
      const a = document.createElement('a')
      a.href = '/file/系统用户导入模板.xls'
      a.setAttribute('download', '系统用户导入模板.xls')
      a.click()
      a.remove()
    },
    /** 用户导入弹窗*/
    handleImportUser() {
      this.$refs['excel-upload-input'].value = null
      this.$refs['excel-upload-input'].click()
    },
    /** 批量导入用户处理*/
    handleClick(e) {
      const files = e.target.files
      const rawFile = files[0]
      if (!rawFile) return
      const formData = new FormData()
      formData.append('file', rawFile)
      uploadAdminExcel(formData).then((res) => {
        if (res.data.errorList.length > 0) {
          this.pageData.page = 1
          this.gridOptions.data = res.data.errorList
          this.errorDialogOption.show = true
          this.findByPage()
        } else if (res.data.finalSuccess === 0) {
          this.$message.warning(`导入用户为0，请检查您的导入数据！`)
        } else {
          this.$message.success(`成功导入${res.data.finalSuccess}位用户！`)
          this.pageData.page = 1
          this.findByPage()
        }
      })
    },
    /** 打开新增或编辑弹窗*/
    openAddDialog(index, row) {
      this.$refs.userEdit.rolesOption = this.rolesOption
      this.$refs.userEdit.showEdit(row || null)
    },
    findByPage() {
      statisticsManager(this.pageData.page, this.pageData.size, this.searchFormData).then((res) => {
        this.tableOptions.data = res.data.result
        this.pageData.total = res.data.total
      })
    },
    /* 删除*/
    handleRemove(index, row) {
      this.$baseConfirm('确认要删除这个用户吗？', null, async() => {
        delManager({ id: row.id }).then(() => {
          this.$message.success('删除用户成功！')
          this.findByPage()
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .tag {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    &.normal {
     background: #1BD09A;
    }
    &.forbid {
      background: #ffbc48;
    }
    &.delete {
      background: #FF5048;
    }
  }
  span {
    margin-left: 8px;
  }
  .normal {
     color: #1BD09A;
   }
 .forbid {
   color: #ffbc48;
 }
 .delete {
   color: #FF5048;
 }
 </style>
